﻿/// <reference path="../Scripts/angular-route.min.js" />
/// <reference path="../Scripts/angular.min.js" />
Type.registerNamespace('SPA_Gallery');

SPA_Gallery.Gallery = function (element) {
    SPA_Gallery.Gallery.initializeBase(this, [element]);

    this._moduleId = null;
    this._clientId = null;

};
SPA_Gallery.Gallery.prototype = {
    initialize: function () {
        SPA_Gallery.Gallery.callBaseMethod(this, 'initialize');
        var currentGalObj = this;
        var currentSF = jQuery.ServicesFramework(this.get_moduleId());
        var currentGalleryApp = angular.module('GApp', ['ngRoute']);
        currentGalleryApp.config(function ($routeProvider, $locationProvider) {
            $locationProvider.hashPrefix('!');
            $routeProvider.when('/', {
                templateUrl: 'templates/lstGalleries.html',
                controller: 'SPALstGalleriesCtl'
            }).when('/Gallery/:galleryId', { redirectTo: '/Gallery/:galleryId/Page/1' })
        .when('/Gallery/:galleryId/Page/:pageId', {
            templateUrl: 'templates/lstGalleries.html', controller: 'SPALstGalleriesCtl'

        }).when('/EditImage/:imageId', {
            templateUrl: 'templates/EditImage.html',
            controller: 'SPAImageCtl'
        }
        ).otherwise({
          redirectTo: '/'
      });
        });
        function SPALstGalleriesCtl($scope, $location, $routeParams) {
          /*  $scope.showG = function (id) {
                $scope.parentGallery = $routeParams.galleryId;
                $location.path("/Gallery/" + encodeURIComponent(id) + "/Page/1");
                $scope.refresh($routeParams.galleryId, 1);
            };*/
          /*  $scope.back = function () {
                var backPath = "/Gallery/" + $scope.parentGallery + "/Page/1";
                if ($scope.parentGallery !== "")
                {
                    $location.path(backPath);
                } else
                { $location.path("/"); }
                $scope.refresh($routeParams.galleryId, 1);
            };*/
            $scope.showFullImage = function (idx, urlFull,initialDescription) {
               // var senderLightBox = this;
                var posTop = jQuery(window).scrollTop() + 25;
                if (initialDescription == null) {
                    initialDescription = "";
                }
                jQuery('body').append('<div id="fjp_overlay"></div>')
                .append('<div id="fjp_lightbox"><img src="' + urlFull + '" /><p class="description">' + initialDescription + '</p><br /><a href="#" id="fjp_light_close">Close X</a><a href="#" id="fjp_light_prev" data-idx="' + idx + '">Prev</a><a href="#" id="fjp_light_next" data-idx="' + idx + '">Next</a></div>');
                jQuery('#fjp_lightbox').css('top', posTop + 'px');

                jQuery("#fjp_light_prev").click(function (e) {
                    e.preventDefault();
                    var currentIdx = jQuery(this).data("idx");
                    currentIdx--;
                    if (currentIdx < 0) {
                        currentIdx = $scope.images.length - 1;
                    }
                    jQuery(this).data("idx", currentIdx);
                    var fullUrl = $scope.images[currentIdx].FullUrl;
                    jQuery("#fjp_lightbox img").remove();
                    var descriptionItem = jQuery("#fjp_lightbox .description");
                    var description = $scope.images[currentIdx].FileDescription;
                    if (description != null) {
                        jQuery("#fjp_lightbox .description").text(description);
                        descriptionItem.show();
                    } else {
                        jQuery("#fjp_lightbox .description")
                        descriptionItem.hide();
                    }
                    jQuery("#fjp_lightbox").prepend("<img src='" + fullUrl + "' />");
                });

                jQuery("#fjp_light_next").click(function (e) {
                    e.preventDefault();
                    var currentIdx = jQuery(this).data("idx");
                    currentIdx++;
                    if (currentIdx >= $scope.images.length) {
                        currentIdx = 0;
                    }
                    jQuery(this).data("idx", currentIdx);
                    var fullUrl = $scope.images[currentIdx].FullUrl;
                    jQuery("#fjp_lightbox img").remove();
                    var descriptionItem = jQuery("#fjp_lightbox .description");
                    var description = $scope.images[currentIdx].FileDescription;
                    if (description != null) {
                        jQuery("#fjp_lightbox .description").text(description);
                        descriptionItem.show();
                    } else {
                        jQuery("#fjp_lightbox .description")
                        descriptionItem.hide();
                    }
                    jQuery("#fjp_lightbox").prepend("<img src='" + fullUrl + "' />");
                });
                jQuery('#fjp_overlay').fadeTo(500, 0.75, function () {
                    jQuery('#fjp_lightbox').fadeTo(250, 1);
                });
                jQuery('#fjp_overlay,  #fjp_light_close').click(function (e) {
                    e.preventDefault();
                    jQuery('#fjp_lightbox').fadeTo(100, 0, function () {
                        jQuery(this).remove();
                        jQuery('#fjp_overlay').fadeTo(250, 0, function () {
                            jQuery(this).remove();
                        });
                    });
                });
            };
            $scope.refresh(decodeURIComponent($routeParams.galleryId), 1);
        }
        function SPAGalleryCtl($scope, $http, $location, $routeParams) {
            $scope.moduleId = currentGalObj.get_moduleId();
            $scope.pageSize = 5;
            $scope.galleries = [];
            $scope.images = [];
            $scope.parentGallery = "";
            $scope.refresh = function (galleryId, pageNum) {
                var config = {
                    headers: {
                        'ModuleId': currentSF.getModuleId(),
                        'TabId': currentSF.getTabId(),
                        "RequestVerificationToken": currentSF.getAntiForgeryValue()
                    }
                };
                var urlG = currentSF.getServiceRoot('SPA_Gallery') + "Gallery/GetGalleries";
                var urlImg = currentSF.getServiceRoot('SPA_Gallery') + "Gallery/GetImages";
                var urlCurrentG = currentSF.getServiceRoot('SPA_Gallery') + "Gallery/GetGallery";
                var paramGId = galleryId;
                if (paramGId === undefined || paramGId === "undefined") { paramGId = ""; }
                var params = { "GalleryId": paramGId, "Page": pageNum };
                $http.post(urlG, params, config).success(function (data, status, headers, config) {
                    // this callback will be called asynchronously
                    // when the response is available
                    $scope.galleries = data;
                }).error(function (data, status, headers, config) {
                    // called asynchronously if an error occurs
                    // or server returns response with an error status.
                });
                $http.post(urlCurrentG, params, config).success(function (data, status, header, config) {
                    $scope.parentGallery = data.GalleryId;
                    $scope.parentId = data.ParentId;
                    $scope.galleryName = data.GalleryName;
                }).error(function (data, status, headers, config) {
                });
                $http.post(urlImg, params, config).success(function (data, status, headers, config) {
                    // this callback will be called asynchronously
                    // when the response is available
                    $scope.images = data;
                    //  $scope.apply();
                }).error(function (data, status, headers, config) {
                    // called asynchronously if an error occurs
                    // or server returns response with an error status.
                });
            };
        }
        function SPAImageCtl($scope, $http, $location, $routeParams) {
          
            $scope.image = null;
            $scope.message = '';
            // $scope.image = getCurrentImage();
            $scope.save = function () {
                var config = {
                    headers: {
                        'ModuleId': currentSF.getModuleId(),
                        'TabId': currentSF.getTabId(),
                        "RequestVerificationToken": currentSF.getAntiForgeryValue()
                    }
                };
                var params = { "currentImage": $scope.image };
                var urlImg = currentSF.getServiceRoot('SPA_Gallery') + "Gallery/SetImage";
                $http.post(urlImg, params, config).success(
                    function (data) {
                        $scope.message = 'Update Success';
                    }
                    ).error(
                    function (data) { $scope.message = 'Error during update'; }
                    );
            };
            $scope.back = function () {
                $location = '/';
                
            };
            $scope.getCurrentImage=function() {
               
                var currentImgId = $routeParams.imageId;
                var config = {
                    headers: {
                        'ModuleId': currentSF.getModuleId(),
                        'TabId': currentSF.getTabId(),
                        "RequestVerificationToken": currentSF.getAntiForgeryValue()
                    }
                };
                var params = { "ImageId": currentImgId};
                var urlImg = currentSF.getServiceRoot('SPA_Gallery') + "Gallery/GetImage";
                $http.post(urlImg, params, config).success(
                    function (data) {
                        $scope.image = data;
                    }
                    ).error(
                    function (data) { $scope.image = null;}
                    );

            };
           $scope.getCurrentImage();
        }

        SPALstGalleriesCtl.$inject = ['$scope', '$location', '$routeParams'];
        SPAImageCtl.$inject = ['$scope', '$http', '$location', '$routeParams'];
        SPAGalleryCtl.$inject = ['$scope', '$http', '$location', '$routeParams'];
        currentGalleryApp.controller('SPALstGalleriesCtl', SPALstGalleriesCtl);
        currentGalleryApp.controller('SPAGalleryCtl', SPAGalleryCtl);
        currentGalleryApp.controller('SPAImageCtl', SPAImageCtl);
        angular.bootstrap(document.getElementById(this.get_clientId()), ['GApp']);

    },
    dispose: function () {
        $clearHandlers(this.get_element());

        SPA_Gallery.Gallery.callBaseMethod(this, 'dispose');
    }, get_moduleId: function () {
        return this._moduleId;
    }, set_moduleId: function (value) {
        this._moduleId = value;
    },
    get_clientId: function () {
        return this._clientId;
    }, set_clientId: function (value) {
        this._clientId = value;
    }

};
SPA_Gallery.Gallery.registerClass('SPA_Gallery.Gallery', Sys.UI.Control);

if (typeof (Sys) !== 'undefined') { Sys.Application.notifyScriptLoaded(); }